﻿using System;
using System.Diagnostics;
using System.Windows.Forms;
using Castle.MicroKernel.ComponentActivator;
using OutlookContactsSync.Domain;
using OutlookContactsSync.Domain.Globals;
using OutlookContactsSync.Domain.Presenters;
using OutlookContactsSync.Domain.Properties;

namespace OutlookContactsSync
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Trace.WriteLine("App started", "info");

            try
            {
                var outlookSyncMainPresenter = DependencyInjection.GetImplementationOf<IOutlookSyncMainPresenter>();
                outlookSyncMainPresenter.InitView();
            }
            catch(ComponentActivatorException ex)
            {
                if (HasOutlookUnavailableException(ex))
                {
                    Trace.TraceError("Cannot start application because Outlook 2010 is unavailable.");
                    MessageBox.Show(Resources.OutlookUnavailable,  "Cannot start application", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    Trace.TraceError("Unhandled exception in Main: {0}", ex.ToString());
                    throw;
                }
            }
        }

        private static bool HasOutlookUnavailableException(Exception ex)
        {
            Exception innerEx = ex.InnerException;
            if (innerEx == null)
            {
                return false;
            }
            else if (innerEx.GetType() == typeof(OutlookUnavailableException))
            {
                return true;
            }
            else
            {
                return HasOutlookUnavailableException(innerEx);
            }
        }
    }
}